package com.teach.util.impl;

import org.springframework.stereotype.Component;

import com.teach.CodeException;
import com.teach.util.PasswordUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;

/**
 * <pre>
 * 密码工具类
 * ClassName : com.wcms.util.PasswordUtil
 * Author : J.L.Zhou
 * Tel : 15111047708
 * E-Mail : 12020042@qq.com
 * Date : 2020-05-03 03:50
 * Version : 1.0
 * </pre>
 */
@Component
public class PasswordUtilImplForMd5 implements PasswordUtil {

	private Digester md5 = new Digester(DigestAlgorithm.MD5);

	@Override
	public String encode(String password) throws CodeException {
		if (StrUtil.hasEmpty(password)) {
			throw new CodeException(20,"密码不能为空");
		}
		return md5.digestHex(password);
	}
	/**
	 * - 含盐值的加密
	 * 
	 * @param password 密码明文
	 * @param salt     盐值
	 * @return
	 */
	public String encode(String password, String salt) {
		if (StrUtil.hasEmpty(password)) {
			throw new CodeException(20,"密码不能为空");
		}
		if (StrUtil.hasEmpty(salt)) {
			throw new CodeException(21,"盐值不能为空");
		}
		return md5.digestHex(password + salt);
	}
	

	/**
	 * - 含盐值的多次加密
	 * 
	 * @param password 密码明文
	 * @param salt     盐值
	 * @param num      加密次数
	 * @return
	 */
	public String encode(String password, String salt, int num) {
		if(num<1) {
			throw new CodeException(22,"加密次数不能小于1");
		}
		String ret = encode(password, salt);
		if (num == 1) {
			return ret;
		} else {
			return encode(ret, salt, num - 1);
		}
	}

}